"""
Celery应用配置
"""

from celery import Celery

from config import settings

# 创建Celery应用
celery = Celery(
    "tete1_sync",
    broker=settings.celery_broker_url,
    backend=settings.celery_result_backend,
    include=["app.tasks.sync_tasks", "app.tasks.verification_tasks", "app.tasks.rollback_tasks", "app.tasks.notification_tasks", "app.tasks.log_tasks"]
)

# 配置Celery
celery.conf.update(settings.celery_config)

# 配置任务路由
celery.conf.task_routes = {
    "app.tasks.sync_tasks.execute_git_sync": {"queue": "git_sync"},
    "app.tasks.verification_tasks.verify_sync_result": {"queue": "verification"},
    "app.tasks.verification_tasks.verify_before_sync": {"queue": "verification"},
    "app.tasks.verification_tasks.schedule_verification_after_sync": {"queue": "verification"},
    "app.tasks.verification_tasks.batch_verification": {"queue": "verification"},
    "app.tasks.rollback_tasks.rollback_execution": {"queue": "rollback"},
    "app.tasks.rollback_tasks.can_rollback": {"queue": "rollback"},
    "app.tasks.rollback_tasks.get_rollback_history": {"queue": "rollback"},
    "app.tasks.rollback_tasks.batch_rollback": {"queue": "rollback"},
    "app.tasks.rollback_tasks.auto_rollback_on_failure": {"queue": "rollback"},
    "app.tasks.rollback_tasks.cleanup_rollback_cache": {"queue": "rollback"},
    "app.tasks.log_tasks.export_logs": {"queue": "logs"},
    "app.tasks.log_tasks.cleanup_old_logs": {"queue": "logs"},
    "app.tasks.log_tasks.generate_log_report": {"queue": "logs"},
    "app.tasks.log_tasks.archive_logs": {"queue": "logs"},
    "app.tasks.notification_tasks.send_task_notification": {"queue": "notifications"},
    "app.tasks.notification_tasks.test_email_configuration": {"queue": "notifications"},
}

# 配置任务优先级
celery.conf.task_default_priority = 5
celery.conf.worker_prefetch_multiplier = 1

# 配置任务超时
celery.conf.task_soft_time_limit = settings.default_task_timeout - 60  # 软超时
celery.conf.task_time_limit = settings.default_task_timeout  # 硬超时

# 配置任务结果过期时间
celery.conf.result_expires = 3600  # 1小时

# 配置任务重试
celery.conf.task_annotations = {
    "*": {"rate_limit": "10/m"},
    "app.tasks.sync_tasks.execute_git_sync": {"rate_limit": "5/m"},
    "app.tasks.rollback_tasks.rollback_execution": {"rate_limit": "3/m"},
    "app.tasks.rollback_tasks.batch_rollback": {"rate_limit": "2/m"},
}

# 配置任务序列化
celery.conf.task_serializer = "json"
celery.conf.accept_content = ["json"]
celery.conf.result_serializer = "json"

# 配置时区
celery.conf.timezone = "UTC"
celery.conf.enable_utc = True